<?php

namespace App\Services;

use AllowDynamicProperties;
use App\Models\WechatConfig;
use EasyWeChat\Kernel\Contracts\AccessToken;
use EasyWeChat\Kernel\Contracts\RefreshableAccessToken;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\Kernel\HttpClient\AccessTokenAwareClient;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\Facades\Log;
use ReflectionException;
use Throwable;

#[AllowDynamicProperties]
class WeChatOfficialAccountService
{
    public function __construct()
    {
        $wechat_config = WechatConfig::query()->first();
        $config = [
            'app_id' => $wechat_config->app_id ?? env('WECHAT_APP_ID'),
            'secret' => $wechat_config->secret ?? env('WECHAT_SECRET'),
            'token' => $wechat_config->token ?? env('WECHAT_TOKEN'),
            'aes_key' => $wechat_config->aes_key ?? env('WECHAT_AES_KEY'),
            'use_stable_access_token' => $wechat_config->use_stable_access_token ?? env('WECHAT_USE_STABLE_ACCESS_TOKEN'),
            'log' => [
                'level' => 'debug',
                'file' => storage_path('logs/wechat.log'),
            ],
        ];
        try {
            $this->app = new Application($config);
        } catch (InvalidArgumentException $e) {
            Log::channel('wechat')->info($e->getMessage());
        }
    }

    public function serve()
    {
        try {
            $server = $this->app->getServer();

            return $server->serve();
        } catch (InvalidArgumentException|ReflectionException|Throwable|BadRequestException|InvalidArgumentException|RuntimeException $e) {
            abort(500, $e->getMessage());
        }
    }

    public function getClient(): AccessTokenAwareClient
    {
        return $this->app->getClient();
    }

    public function getAccessToken(): AccessToken|RefreshableAccessToken
    {
        return $this->app->getAccessToken();
    }
}
